<?php

namespace app\site\controller;

use app\common\model\ShopAttrModel;
use app\common\model\ShopCombinationModel;
use app\common\model\ShopExtendModel;
use app\common\model\ShopGoodsBrandModel;
use app\common\model\ShopGoodsDataModel;
use app\common\model\ShopGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use app\common\model\UserModel;
use app\common\model\SiteModel;
use org\util\TreeUtil;
use think\Db;
use think\Request;

class ShopGoodsController extends BaseController
{

    private $goodsCategoryCache;
    private $goodsModel;
    private $goodsDataModel;
    private $goodsSkuModel;
    private $extendModel;
    private $attrModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->goodsModel         = new ShopGoodsModel();
        $this->goodsDataModel     = new ShopGoodsDataModel();
        $this->extendModel        = new ShopExtendModel();
        $this->goodsSkuModel      = new ShopGoodsSkuModel();
        $this->goodsCategoryCache = $this->getCategory();
        $this->attrModel          = new ShopAttrModel();
    }

    /**
     * 获取站点分组
     */
    public function getSiteGroup()
    {
        $list    = cache('shop_site_group' . $this->getSiteId());
        $catList = TreeUtil::tree($list, 'cat_name', 'cid');
        return $catList;
    }

    /**
     * 获取允许操作栏目
     * @param $siteId
     * @param $uid
     * @return array|mixed
     */
    public function getCategory()
    {
        $userModel = new UserModel();
        $category  = $userModel->getGoodsCategory($this->getGroupId());
        return $category;
    }

    /**
     * 首页
     */
    public function index()
    {
        $map              = [];
        $query            = $this->request->request();
        if($this->request->has('is_commend')){
            $isCommend = $this->request->param('is_commend');
            $query['is_commend'] = $isCommend;
            $map['is_commend'] = $isCommend;
            $map['is_on_sale'] = 1;
        }
        $is_on_sale = $this->request->param('is_on_sale',1);
        $map['site_id']   = $this->getSiteId();
        $map['is_on_sale'] = $is_on_sale; //出售中商品
        $goodsName = $this->request->param('goods_name');
        if (!empty($goodsName)) {
            $map['goods_name']   = ['like', '%' . $goodsName . '%'];
        }
        $siteCid = $this->request->param('site_cid');
        if ($siteCid > 0) {
            $siteCids          = array_keys(\org\util\TreeUtil::channelList($this->getSiteGroup(), $siteCid, "&nbsp;", 'cid', 'pid'));
            $siteCids[]        = $siteCid; //加入当前栏目
            $map['site_cid']   = ['in', $siteCids];
        }
        $list = $this->goodsModel->where($map)->order('goods_id desc')->paginate(12, false, [
            'query' => $query,
        ]);
        //echo $this->goodsModel->getLastSql();
        cookie('__GOODSURL__', get_current_url());
        $this->assign('siteGroup', $this->getSiteGroup());
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $data['uid']     = $this->getUid();
            $data['site_id'] = $this->getSiteId();
            //冗余站点信息
            $siteModel           = new SiteModel();
            $siteInfo            = $siteModel->field('site_name,is_own_shop')->where('site_id', $data['site_id'])->find();
            $data['site_name']   = $siteInfo['site_name'];
            $data['is_own_shop'] = $siteInfo['is_own_shop']; //是否平台自营
            //冗余品牌名称
            if ($data['brand_id'] > 0) {
                $brandModel         = new ShopGoodsBrandModel();
                $data['brand_name'] = $brandModel->where('brand_id', $data['brand_id'])->value('brand_name');
            }
            $result = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $result = $this->goodsModel->addData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('添加成功', cookie('__GOODSURL__'));
        }
        $attrList = $this->attrModel->where('site_id', $this->getSiteId())->order('attr_sort')->select();
        $this->assign('attrList', $attrList);
        $this->assign('unitList', get_dict('103'));
        $this->assign('goodsCategory', $this->formatCategory());
        $this->assign('siteGroup', $this->getSiteGroup());
        return $this->fetch();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data            = $this->request->param();
            $data['site_id'] = $this->getSiteId();
            //冗余品牌名称
            if ($data['brand_id'] > 0) {
                $brandModel         = new ShopGoodsBrandModel();
                $data['brand_name'] = $brandModel->where('brand_id', $data['brand_id'])->value('brand_name');
            }
            $result = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $result = $this->goodsModel->editData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('操作成功！', cookie('__GOODSURL__'));
        }
        $goodsId  = $this->request->param('goods_id/d');
        $info     = $this->goodsModel->getInfo($goodsId);
        $attrList = $this->attrModel->where('site_id', $this->getSiteId())->order('attr_sort')->select();
        $this->assign('info', $info);
        $this->assign('attrList', $attrList);
        $this->assign('unitList', get_dict('103'));
        $this->assign('goodsCategory', $this->formatCategory());
        $this->assign('siteGroup', $this->getSiteGroup());
        return $this->fetch();
    }


    /**
     * 拷贝商品
     * @return mixed
     */
    public function copy()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            unset($data['goods_id']);
            $data['uid']     = $this->getUid();
            $data['site_id'] = $this->getSiteId();
            //冗余站点名称
            $siteModel         = new SiteModel();
            $data['site_name'] = $siteModel->where('site_id', $data['site_id'])->value('site_name');
            //冗余品牌名称
            if ($data['brand_id'] > 0) {
                $brandModel         = new ShopGoodsBrandModel();
                $data['brand_name'] = $brandModel->where('brand_id', $data['brand_id'])->value('brand_name');
            }
            $result = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $result = $this->goodsModel->addData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('拷贝成功', cookie('__GOODSURL__'));
        }
        $goodsId  = $this->request->param('goods_id/d');
        $info     = $this->goodsModel->getInfo($goodsId);
        $attrList = $this->attrModel->where('site_id', $this->getSiteId())->order('attr_sort')->select();
        $this->assign('info', $info);
        $this->assign('attrList', $attrList);
        $this->assign('unitList', get_dict('103'));
        $this->assign('goodsCategory', $this->formatCategory());
        $this->assign('siteGroup', $this->getSiteGroup());
        return $this->fetch();
    }


    /**
     * 商品批量设置
     */
    public function batchEdit()
    {
        if ($this->request->isAjax()) {
            $skuList   = $this->request->param('sku_list/a');
            $goodsList = $this->request->param('goods_list/a');
            if ($goodsList) {
                $dataList = [];
                foreach ($goodsList as $k => $v) {
                    $v['goods_id'] = $k;
                    $dataList[]    = $v;
                }
                $this->goodsModel->saveAll($dataList);
            }
            if ($skuList) {
                $dataList = [];
                foreach ($skuList as $k => $v) {
                    $v['sku_id'] = $k;
                    $dataList[]  = $v;
                }
                $this->goodsSkuModel->saveAll($dataList);
            }
            $this->success('操作成功！');
        }
        $map       = [];
        $goodsName = $this->request->param('goods_name', '');
        if (!empty($goodsName)) {
            $map['goods_name']   = ['like', '%' . $goodsName . '%'];
            $query['goods_name'] = $goodsName;
        }
        $siteCid = $this->request->param('site_cid');
        if ($siteCid > 0) {
            $siteCids          = array_keys(\org\util\TreeUtil::channelList($this->getSiteGroup(), $siteCid, "&nbsp;", 'cid', 'pid'));
            $siteCids[]        = $siteCid; //加入当前栏目
            $map['site_cid']   = ['in', $siteCids];
            $query['site_cid'] = $siteCid;
        }
        $map['site_id'] = $this->getSiteId();
        $list           = $this->goodsModel->alias('t1')
            ->field('*')
            ->join('shop_goods_sku t2', 't1.goods_id=t2.goods_id')
            ->where($map)
            ->order('goods_sort desc')
            ->paginate(12, false, [
                'query' => $query,
            ]);
        $this->assign('siteGroup', $this->getSiteGroup());
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 批量调价
     */
    public function batchPrice()
    {
        if ($this->request->isAjax()) {
            $siteCids     = $this->request->param('site_cids/a');
            $marketChange = $this->request->param('market_change');
            $marketValue  = $this->request->param('market_value');
            $marketType   = $this->request->param('market_type');

            $goodsChange = $this->request->param('goods_change');
            $goodsValue  = $this->request->param('goods_value');
            $goodsType   = $this->request->param('goods_type');
            if (!empty($siteCids)) {
                $map['site_cid'] = ['in', $siteCids];
                $goodsIds        = $this->goodsModel->where($map)->column('goods_id');
                if ($goodsIds) {
                    $goodsIds = implode(',', $goodsIds);
                } else {
                    $this->error('未找到匹配商品！');
                }
                if ($marketValue > 0) {
                    $calc        = $marketChange == 'up' ? '+' : '-';
                    $changeValue = $marketType == '100' ? "market_price{$calc}market_price*($marketValue/$marketType)" : "market_price{$calc}$marketValue";
                    $marketField = "market_price=$changeValue ";
                    $sql         = "update shop_goods_sku set {$marketField} where goods_id in ({$goodsIds})";
                    Db::execute($sql);
                }
                if ($goodsValue > 0) {
                    $priceList = $this->goodsSkuModel->where('goods_id', 'in', $goodsIds)->column('goods_price', 'sku_id');
                    if ($priceList) {
                        foreach ($priceList as $skuId => $goodsPrice) {
                            $changeValue = $goodsType == '1' ? $goodsValue : $goodsPrice * ($goodsValue / $goodsType);
                            if (strstr($goodsPrice, ':') === false) { //正常价格
                                if ($goodsChange == 'up') {
                                    $goodsPrice = $goodsPrice + $changeValue;
                                } else {
                                    $goodsPrice = $goodsPrice - $changeValue;
                                }
                            } else { //阶梯价
                                $priceArr = explode(',', $goodsPrice);
                                foreach ($priceArr as $v) {
                                    $arr = explode(":", $v);
                                    if ($goodsChange == 'up') {
                                        $arr[1] = $arr[1] + $changeValue;
                                    } else {
                                        $arr[1] = $arr[1] - $changeValue;
                                    }
                                    $price[] = implode(':', $arr);
                                }
                                $goodsPrice = implode(',', $price);
                            }
                            $dataList[] = ['sku_id' => $skuId, 'goods_price' => $goodsPrice];
                        }
                        if ($dataList) {
                            $this->goodsSkuModel->saveAll($dataList);
                        }
                    }
                }
                $this->success('操作成功！');
            } else {
                $this->error('请选择要调价分组！');
            }
        }
        $this->assign('siteGroup', $this->getSiteGroup());
        return $this->fetch();
    }

    /**
     * 设置状态
     */
    public function setStatus()
    {
        $goodsId = $this->request->param('goods_id');
        $field   = $this->request->param('field');
        $status  = $this->request->param('status');
        $this->goodsModel->where('goods_id', $goodsId)->setField($field, $status);
        $this->success('切换状态成功！');
    }

    /**
     * 删除
     */
    public function del()
    {
        $goodsId = $this->request->param('goods_id/d');
        $this->goodsModel->delData($goodsId);
        $this->success('删除成功！');
    }

    /**
     *排序
     */
    public function updateOrder()
    {
        $listOrder = $this->request->param('list_order/a');
        foreach ($listOrder as $goods_id => $goods_sort) {
            $goodsId    = intval($goods_id);
            $goodsSort  = intval($goods_sort);
            $dataList[] = ["goods_id" => $goodsId, "goods_sort" => $goodsSort];
        }
        $this->goodsModel->saveAll($dataList);
        $this->success('排序成功！');
    }

    /**
     * 删除单条SKU
     */
    public function delSku()
    {
        $skuId = $this->request->param('sku_id');
        $this->goodsSkuModel->delData($skuId);
        $this->success('操作成功！');
    }

    /**
     * 阶梯价
     */
    public function ladderprice()
    {
        return $this->fetch();
    }

    /**
     * 获取销售属性
     */
    public function getAttr()
    {
        $goodsId = $this->request->param('goods_id/d', 0);
        $attrId  = $this->request->param('attr_id/d', 0);
        if ($goodsId > 0) { //编辑页面
            $skulist = $this->goodsSkuModel->where('goods_id', $goodsId)->select();
            $this->assign('skulist', $skulist);
        }
        $isShow   = 0; //不显示SKU属性
        $attrList = [];
        if ($attrId > 0) {
            $attrList = $this->attrModel->getAttrList($attrId);
            $isShow   = 1; //显示SKU属性
        }
        $this->assign('isShow', $isShow);
        $this->assign('attrList', $attrList);
        echo $this->fetch();
    }

    /**
     * 获取指定栏目下品牌
     * @return \think\response\Json
     */
    public function getCidBrand()
    {
        $brandModel = new ShopGoodsBrandModel();
        $brandList  = [];
        $cid        = $this->request->param('cid/d');
        $list       = $brandModel
            ->where('site_id', $this->getSiteId())
            ->where("find_in_set('{$cid}',cid_path)")
            ->order('brand_sort desc')
            ->select();
        if (!$list->isEmpty()) {
            $brandList = $list;
        }
        return json($brandList);
    }

    /**
     * 获取搜索属性html
     */
    public function extend()
    {
        $goodsId  = $this->request->param('goods_id', 0);
        $cid      = $this->request->param('cid');
        $formHtml = $this->extendModel->getExtendHtml($cid, $goodsId);
        echo $formHtml;
    }

    /**
     * 格式化商品类目
     * @return array
     */
    private function formatCategory()
    {
        $cat = [];
        foreach ($this->goodsCategoryCache as $v) {
            //排除外部链接
            if ($v['cat_type'] == 3) {
                continue;
            }
            if ($v['cat_type'] == 1) { //频道页不允许添加内容
                $v['disabled'] = ' disabled';
            } else {
                $v['disabled'] = '';
            }
            $cat[] = $v;
        }
        return $cat;
    }

}
